package com.dotnet.modules.order.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dotnet.common.utils.Constants;
import com.dotnet.common.web.BaseController;
import com.dotnet.modules.compact.entity.ContractType;
import com.dotnet.modules.compact.service.ContractTypeService;
import com.dotnet.modules.field.entity.FieldPrice;
import com.dotnet.modules.field.entity.ProductField;
import com.dotnet.modules.field.entity.ProductFieldValue;
import com.dotnet.modules.field.service.FieldPriceService;
import com.dotnet.modules.field.service.ProductFieldService;
import com.dotnet.modules.field.service.ProductFieldValueService;
import com.dotnet.modules.order.entity.Order;
import com.dotnet.modules.order.entity.OrderFieldPriceVo;
import com.dotnet.modules.order.entity.OrderFieldVo;
import com.dotnet.modules.order.entity.OrderPageVo;
import com.dotnet.modules.order.entity.OrderPassVo;
import com.dotnet.modules.order.entity.OrderProductCustomer;
import com.dotnet.modules.order.entity.OrderProductWeb;
import com.dotnet.modules.order.entity.OrderVo;
import com.dotnet.modules.order.entity.PayCycle;
import com.dotnet.modules.order.service.OrderProductCustomerService;
import com.dotnet.modules.order.service.OrderProductWebService;
import com.dotnet.modules.order.service.OrderService;
import com.dotnet.modules.product.entity.ProductInfo;
import com.dotnet.modules.product.service.ProductInfoService;
import com.page.Pagination;
import com.shishuo.cdn.dao.UserBankLogDao;
import com.shishuo.cdn.dao.UserDao;
import com.shishuo.cdn.entity.User;

@Controller
@RequestMapping("/web/order")
public class OrderController extends BaseController {
	
	@Autowired
	private ContractTypeService contractTypeService;

	@Autowired
	private OrderProductWebService opwService;

	@Autowired
	private OrderProductCustomerService opcService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private ProductInfoService productService;

	@Autowired
	private ProductFieldService pfService;

	@Autowired
	private ProductFieldValueService pfvService;

	@Autowired
	private FieldPriceService fpService;

	@Autowired
	private UserDao userDao;

	@Autowired
	private UserBankLogDao userBankLogDao;

	@Autowired
	private OrderProductCustomerService opcCustomerService;

	/**
	 * 
	 * 描述：添加产品
	 * 创建人： 魏泽超
	 * 创建时间: 2016-6-6 下午2:48:36
	 * @version
	 */
	@ResponseBody
	@RequestMapping("/addProduct")
	public Map<String, Object> addProduct(OrderVo orderVo, String productId) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (null != orderVo && StringUtils.isNotBlank(productId)) {
			try {
				OrderProductWeb opw = new OrderProductWeb();
				opw.setOrderNo(orderVo.getOrderNo());
				opw.setProductId(productId);
				OrderProductWeb opwEntity = opwService.queryOne(opw);
				if (null == opwEntity) {
					addOrderProductWeb(orderVo, productId);
					map.put("status", true);
					map.put("msg", "产品添加成功!");
				} else {
					map.put("status", false);
					map.put("msg", "请勿重复提交产品!");
				}
			} catch (Exception e) {
				// TODO: handle exception
				logger.info("添加产品异常");
				map.put("status", false);
			}
		}
		return map;
	}

	/**
	 * 
	 * 描述：添加订单
	 * 创建人： 魏泽超
	 * 创建时间: 2016-6-6 下午2:48:30
	 * @version
	 */
	@ResponseBody
	@RequestMapping("/addOrder")
	public Map<String, Object> addOrder(Order order, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		boolean flag = false;
		if (order != null) {
			order.setCreateTime(new Date());
			order.setEffectiveTime(new Date());
			order.setOrderStatus(Integer.valueOf(0));
			order.setUserAccount(getloginUser(request).getReg_tel());
			order.setIsDelete(Integer.valueOf(0));
			int i = orderService.add(order);
			if (i > 0) {
				flag = true;
				map.put("status", flag);
				map.put("msg", "订单填写完成，点击确定后跳转到订单列表");
			} else {
				map.put("status", flag);
				map.put("msg", "订单填写失败!");
			}
		}
		return map;
	}

	/**
	 * 
	 * 描述：添加产品
	 * 创建人： 魏泽超
	 * 创建时间: 2016-6-6 下午2:48:44
	 * @version
	 */
	private void addOrderProductWeb(OrderVo orderVo, String productId) {
		ProductInfo product = new ProductInfo();
		product.setId(Integer.valueOf(productId));
		ProductInfo queryOne = productService.queryOne(product);
		if (null != queryOne) {
			OrderProductWeb opw = new OrderProductWeb();
			opw.setCreateTime(new Date());
			opw.setCheckTime(new Date());
			opw.setOrderNo(orderVo.getOrderNo());
			opw.setPaymentType(orderVo.getPaymentType());
			opw.setProductField(orderVo.getProductField());
			opw.setProductPrice(orderVo.getProductPrice());
			opw.setProductTime(orderVo.getProductTime());
			// 商品信息
			opw.setProductName(queryOne.getProductName());
			opw.setProductType(queryOne.getProductType());
			opw.setProductStatus(Integer.valueOf(0));
			opw.setProductId(productId);
			int i = opwService.add(opw);
			if (i > 0) {
				addOrderProductCustomer(orderVo, productId);
			}
		}
	}

	/**
	 * 
	 * 描述：添加产品
	 * 创建人： 魏泽超
	 * 创建时间: 2016-6-14 上午9:48:51
	 * @version
	 */
	private void addOrderProductCustomer(OrderVo orderVo, String productId) {
		ProductInfo product = new ProductInfo();
		product.setId(Integer.valueOf(productId));
		ProductInfo queryOne = productService.queryOne(product);
		if (null != queryOne) {
			OrderProductCustomer opw = new OrderProductCustomer();
			opw.setCreateTime(new Date());
			opw.setCheckTime(new Date());
			opw.setOrderNo(orderVo.getOrderNo());
			opw.setPaymentType(orderVo.getPaymentType());
			opw.setProductField(orderVo.getProductField());
			opw.setProductPrice(orderVo.getProductPrice());
			opw.setProductTime(orderVo.getProductTime());
			// 商品信息
			opw.setProductName(queryOne.getProductName());
			opw.setProductType(queryOne.getProductType());
			opw.setProductStatus(Integer.valueOf(0));
			opw.setProductId(productId);
			opcService.add(opw);
		}
	}

	/**
	 * 
	 * 描述：订单列表
	 * 创建人： 魏泽超
	 * 创建时间: 2016-6-16 上午11:18:43
	 * @version
	 * @throws Exception 
	 */
	@RequestMapping("/orderList")
	public String getOrderList(Order o, ModelMap model, HttpServletRequest request, Integer pageNo, String startDate, String endDate) throws Exception {
		User user = getloginUser(request);
		StringBuilder params = new StringBuilder();
		OrderPageVo order = new OrderPageVo();
		SimpleDateFormat sd = new SimpleDateFormat("MM/dd/yyyy");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (null != startDate && StringUtils.isNotBlank(startDate) && null != endDate && StringUtils.isNotBlank(endDate)) {
			params.append("&startDate=").append(startDate).append("&endDate=").append(endDate);
			order.setCreateTime(sdf.parse(sdf.format(sd.parse(startDate))));
			order.setEndTime(sdf.parse(sdf.format(sd.parse(endDate))));
		}

		if (null != o.getOrderNo() && StringUtils.isNotBlank(o.getOrderNo())) {
			order.setOrderNo(o.getOrderNo());
			params.append("&orderNo=").append(o.getOrderNo());
		}

		if (null != o.getOrderStatus() && StringUtils.isNotBlank(o.getOrderStatus().toString())) {
			order.setOrderStatus(o.getOrderStatus());
			params.append("&orderStatus=").append(o.getOrderStatus());
		}
		
		if(null!=user){
			order.setUserAccount(user.getReg_tel());
		}
		
		// 如果页号为null 或小于1 设为1
		order.setPageNo(Pagination.cpn(pageNo));
		// order.setPageSize(Constants.PAGE_SIZE);
		order.setPageSize(3);
		order.setIsDelete(0);
		// order.setOrderStatus(0);
		Pagination pagination = orderService.pagelist(order);
		// 分页展示
		String url = request.getContextPath() + "/web/order/orderList.do";
		pagination.pageView(url, params.toString());
		model.put("page", pagination);
		model.put("order", o);
		model.put("endDate", endDate);
		model.put("startDate", startDate);
		return "/order/business";
	}

	/**
	 *  
	 * 描述：订单详情
	 * 创建人： 魏泽超
	 * 创建时间: 2016-6-14 上午10:35:02
	 * @version
	 */
	@RequestMapping("/orderdetail")
	public String orderDetail(ModelMap model, String orderNo, String type) {
		logger.info("--进入订单详情方法---orderDetail");
		// 先查询 此订单是否已审核通过
		Order o = new Order();
		o.setOrderNo(orderNo);
		Order orderEntity = orderService.queryOne(o);
		List<OrderPassVo> orderPassVo = new ArrayList<OrderPassVo>();
		if (null != orderEntity) {
			if (0 == orderEntity.getOrderStatus() || 7 == orderEntity.getOrderStatus() || "1".equals(type)) {
				if ("1".equals(type)) {
					logger.info("查询历史订单信息");
				} else {
					logger.info("订单未通过审核");
				}
				// 如果未通过就查询 未审核的产品 -- 历史数据
				OrderProductWeb opw = new OrderProductWeb();
				opw.setOrderNo(orderNo);
				List<OrderProductWeb> queryAll = opwService.queryAll(opw);
				if (null != queryAll && queryAll.size() > 0) {
					createOrderFieldListNotPass(queryAll, orderPassVo);
				}
			} else {
				logger.info("订单已通过审核");
				// 如果通过 就查询已审核的产品 --最新数据
				OrderProductCustomer opc = new OrderProductCustomer();
				opc.setOrderNo(orderNo);
				opc.setProductStatus(1);
				List<OrderProductCustomer> queryAll = opcService.queryAll(opc);
				if (null != queryAll && queryAll.size() > 0) {
					createOrderFieldList(queryAll, orderPassVo);
				}
			}
		}
		model.put("opc", orderPassVo);

		Order order = new Order();
		order.setOrderNo(orderNo);
		Order queryOne = orderService.queryOne(order);
		if (null != queryOne) {
			model.put("order", queryOne);
		}
		return "/order/orderdetail";
	}

	@ResponseBody
	@RequestMapping("/cancleOrder")
	public Map<String, Object> cancleOrder(Order order) {

		Map<String, Object> map = new HashMap<String, Object>();
		int i = orderService.updateByPrimaryKeySelective(order);
		if (i > 0) {
			map.put("result", true);
		} else {
			map.put("result", false);
		}
		return map;
	}

	/**
	 * 
	 * 描述：付款
	 * 创建人： 魏泽超
	 * 创建时间: 2016-6-15 下午4:56:38
	 * @version
	 */
	@ResponseBody
	@RequestMapping("/payOrder")
	public Map<String, Object> payOrder(HttpServletRequest request, HttpServletResponse response, Order order) {
		logger.info("进入支付方法");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		double rest_money;
		User user = (User) request.getSession().getAttribute("user");
		user = userDao.getUserById(user.getReg_tel());

		Map<String, Object> map = new HashMap<String, Object>();

		// 查询产品总价
		double productPrice = 0.0;
		OrderProductCustomer opc = new OrderProductCustomer();
		opc.setOrderNo(order.getOrderNo());
		opc.setProductStatus(1);
		List<OrderProductCustomer> opcAll = opcService.queryAll(opc);
		String productNames = "";
		if (null != opcAll && opcAll.size() > 0) {
			for (OrderProductCustomer opcEntity : opcAll) {
				productNames = productNames + opcEntity.getProductName() + ",";
				productPrice = productPrice + opcEntity.getProductPrice().doubleValue();
			}
		}
		rest_money = Double.valueOf(user.getBalance().toString()) - productPrice;
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		if (rest_money >= 0.0) {
			user.setBalance(new BigDecimal(rest_money));
			map.put("balance", rest_money + "");
			map.put("userId", user.getUser_id().toString());
			userDao.updateBalanceById(map);

			order.setOrderStatus(2); // 将订单状态改为已付款状态
			int i = orderService.updateByPrimaryKeySelective(order);
			if (i > 0) {
				/*****保存到账户变更日志*******/
				paramsMap.put("bank_money", (0.0 - productPrice) + "");
				paramsMap.put("user_id", user.getUser_id().toString());
				paramsMap.put("type", "3");// ？？
				paramsMap.put("order_sn", order.getOrderNo());
				paramsMap.put("create_time", new Date());
				paramsMap.put("description", productNames);
				paramsMap.put("status", "1");

				paramsMap.put("kf_refund", "0");// 默认数据
				paramsMap.put("cw_refund", "0");
				paramsMap.put("gl_name", "");
				userBankLogDao.addUserBankLog(paramsMap);// 创建订单
			}
			resultMap.put("status", true);
			resultMap.put("balance", "付款成功");
		} else {
			resultMap.put("balance", "余额不足，请充值");
			resultMap.put("status", false);
		}
		return resultMap;
	}

	/**
	 * 
	 * 描述：私有方法，拼装数据 --已通过审核
	 * 创建人： 魏泽超
	 * 创建时间: 2016-6-15 上午9:53:25
	 * @version
	 */
	private void createOrderFieldList(List<OrderProductCustomer> queryAll, List<OrderPassVo> orderPassVo) {
		for (OrderProductCustomer opc : queryAll) {
			OrderPassVo opVo = new OrderPassVo();
			opVo.setId(opc.getId());
			opVo.setCheckTime(opc.getCheckTime());
			opVo.setCreateTime(opc.getCreateTime());
			opVo.setOrderNo(opc.getOrderNo());
			opVo.setPaymentType(opc.getPaymentType());
			opVo.setProductId(opc.getProductId());
			opVo.setProductName(opc.getProductName());
			opVo.setProductPrice(opc.getProductPrice());
			opVo.setProductStatus(opc.getProductStatus());
			opVo.setProductTime(opc.getProductTime());
			String productField = opc.getProductField();
			// json转为map
			Map<String, Object> map = toMap(productField);
			ProductField pf = new ProductField();
			pf.setProductId(Integer.valueOf(opc.getProductId()));
			pf.setIsDelete(0);
			pf.setIsUse(1);
			// 查询 所属产品的属性集合
			List<ProductField> pfquery = pfService.queryAll(pf);

			List<OrderFieldVo> orderFieldVoList = new ArrayList<OrderFieldVo>();

			// 创建field集合
			createOrderFieldVo(map, orderFieldVoList, pfquery);

			opVo.setOrderFieldList(orderFieldVoList);

			orderPassVo.add(opVo);
		}
	}

	/**
	 * 
	 * 描述：私有方法，拼装数据 --未通过审核
	 * 创建人： 魏泽超
	 * 创建时间: 2016-6-15 上午9:53:25
	 * @version
	 */
	private void createOrderFieldListNotPass(List<OrderProductWeb> queryAll, List<OrderPassVo> orderPassVo) {
		for (OrderProductWeb opc : queryAll) {
			OrderPassVo opVo = new OrderPassVo();
			opVo.setId(opc.getId());
			opVo.setCheckTime(opc.getCheckTime());
			opVo.setCreateTime(opc.getCreateTime());
			opVo.setOrderNo(opc.getOrderNo());
			opVo.setPaymentType(opc.getPaymentType());
			opVo.setProductId(opc.getProductId());
			opVo.setProductName(opc.getProductName());
			opVo.setProductPrice(opc.getProductPrice());
			opVo.setProductStatus(opc.getProductStatus());
			opVo.setProductTime(opc.getProductTime());
			String productField = opc.getProductField();
			// json转为map
			Map<String, Object> map = toMap(productField);
			ProductField pf = new ProductField();
			pf.setProductId(Integer.valueOf(opc.getProductId()));
			pf.setIsDelete(0);
			pf.setIsUse(1);
			// 查询 所属产品的属性集合
			List<ProductField> pfquery = pfService.queryAll(pf);

			List<OrderFieldVo> orderFieldVoList = new ArrayList<OrderFieldVo>();

			// 创建field集合
			createOrderFieldVo(map, orderFieldVoList, pfquery);

			opVo.setOrderFieldList(orderFieldVoList);

			orderPassVo.add(opVo);
		}
	}

	/**
	 * 
	 * 描述：私有方法，拼装数据
	 * 创建人： 魏泽超
	 * 创建时间: 2016-6-15 上午9:53:48
	 * @version
	 */
	private void createOrderFieldVo(Map<String, Object> map, List<OrderFieldVo> orderFieldVoList, List<ProductField> pfquery) {
		for (String key : map.keySet()) {
			for (ProductField pfentity : pfquery) {
				if (key.equals(pfentity.getInputName())) {
					if ("radio".equals(pfentity.getFieldType()) || "select".equals(pfentity.getFieldType())) {
						OrderFieldVo ofVo = new OrderFieldVo();
						ofVo.setFieldName(pfentity.getFieldName());
						ofVo.setFieldType(pfentity.getFieldType());
						ofVo.setFieldValue(map.get(key).toString());
						ofVo.setInputName(pfentity.getInputName());
						ofVo.setIsSum(pfentity.getIsSum());
						ProductFieldValue pfv = new ProductFieldValue();
						pfv.setFieldId(pfentity.getId());
						List<ProductFieldValue> queryAll2 = pfvService.queryAll(pfv);
						List<OrderFieldPriceVo> fieldValue = new ArrayList<OrderFieldPriceVo>();
						if (null != queryAll2 && queryAll2.size() > 0) {
							for (int i = 0; i < queryAll2.size(); i++) {
								OrderFieldPriceVo fpVo = new OrderFieldPriceVo();
								fpVo.setId(queryAll2.get(i).getId().toString().toString());
								fpVo.setValue(queryAll2.get(i).getFieldValue());
								fieldValue.add(fpVo);
							}
						}

						List<OrderFieldPriceVo> fieldPrice = new ArrayList<OrderFieldPriceVo>();
						for (ProductFieldValue pfValue : queryAll2) {
							FieldPrice fp = new FieldPrice();
							fp.setFieldValueId(pfValue.getId());
							fp.setIsDelete(0);
							fp.setIsUse(1);
							FieldPrice queryOne = fpService.queryOne(fp);
							if (null != queryOne) {
								OrderFieldPriceVo fpVo = new OrderFieldPriceVo();
								fpVo.setId(queryOne.getFieldValueId().toString());
								fpVo.setValue(queryOne.getFieldPrice().toString());
								fpVo.setFieldValue(queryOne.getFieldValue());
								fpVo.setInputName(pfentity.getInputName());
								ofVo.setFieldValue(Float.valueOf(map.get(key).toString()).toString());
								fieldPrice.add(fpVo);
							}
						}

						ofVo.setFieldTypeValuePrice(fieldPrice);
						ofVo.setFieldTypeValue(fieldValue);
						orderFieldVoList.add(ofVo);
					} else if ("checkbox".equals(pfentity.getFieldType())) {
						OrderFieldVo ofVo = new OrderFieldVo();
						ofVo.setFieldName(pfentity.getFieldName());
						ofVo.setFieldType(pfentity.getFieldType());
						ofVo.setFieldValue(map.get(key).toString());
						ofVo.setInputName(pfentity.getInputName());
						ofVo.setIsSum(pfentity.getIsSum());
						ProductFieldValue pfv = new ProductFieldValue();
						pfv.setFieldId(pfentity.getId());
						List<ProductFieldValue> queryAll2 = pfvService.queryAll(pfv);
						List<OrderFieldPriceVo> fieldValue = new ArrayList<OrderFieldPriceVo>();
						if (null != queryAll2 && queryAll2.size() > 0) {
							for (int i = 0; i < queryAll2.size(); i++) {
								OrderFieldPriceVo fpVo = new OrderFieldPriceVo();
								fpVo.setId(queryAll2.get(i).getId().toString().toString());
								fpVo.setValue(queryAll2.get(i).getFieldValue());
								fieldValue.add(fpVo);
							}
						}

						List<OrderFieldPriceVo> fieldPrice = new ArrayList<OrderFieldPriceVo>();
						List<String> str = new ArrayList<String>();
						for (ProductFieldValue pfValue : queryAll2) {
							FieldPrice fp = new FieldPrice();
							fp.setFieldValueId(pfValue.getId());
							fp.setIsDelete(0);
							fp.setIsUse(1);
							FieldPrice queryOne = fpService.queryOne(fp);
							if (null != queryOne) {
								OrderFieldPriceVo fpVo = new OrderFieldPriceVo();
								fpVo.setId(queryOne.getFieldValueId().toString());
								fpVo.setValue(queryOne.getFieldPrice().toString());
								fpVo.setFieldValue(queryOne.getFieldValue());
								fpVo.setInputName(pfentity.getInputName());
								if (map.get(key).toString().contains(queryOne.getFieldPrice().intValue() + "")) {
									str.add(queryOne.getFieldValue());
								}
								// ofVo.setFieldValue(Float.valueOf(map.get(key).toString()).toString());
								fieldPrice.add(fpVo);
							}
						}
						ofVo.setFieldValue(str.toString());
						ofVo.setFieldTypeValuePrice(fieldPrice);
						ofVo.setFieldTypeValue(fieldValue);
						orderFieldVoList.add(ofVo);
					} else {
						OrderFieldVo ofVo = new OrderFieldVo();
						ofVo.setFieldName(pfentity.getFieldName());
						ofVo.setFieldType(pfentity.getFieldType());
						ofVo.setFieldValue(map.get(key).toString());
						ofVo.setInputName(pfentity.getInputName());
						orderFieldVoList.add(ofVo);
					}
				}
			}
		}
	}

	/**  
	    * 将json格式的字符串解析成Map对象 <li>  
	    * json格式：{"name":"admin","retries":"3fff","testname"  
	    * :"ddd","testretries":"fffffffff"}  
	    */
	private static Map<String, Object> toMap(String json) {
		// JSON -> Map
		// Map<String, Object> map1 = (Map<String, Object>) JSON.parse(json);
		LinkedHashMap<String, Object> map1 = JSON.parseObject(json, new TypeReference<LinkedHashMap<String, Object>>() {
		});
		for (String key : map1.keySet()) {
			/* System.out.println(key + ":" + map1.get(key)); */
		}
		return map1;
	}

	/**
	 * 
	 * 描述:付费周期
	 * 创建人： 王小雷
	 * 创建时间: 2016-7-1 下午5:52:12
	 * @version
	 */

	@RequestMapping(value = "/paycycle")
	public String paycycle(String orderNo, Integer pageNo, HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		OrderProductCustomer opc = new OrderProductCustomer();
		PayCycle pc = new PayCycle();
		// 拿到订单号
		opc.setOrderNo(orderNo);
		List<OrderProductCustomer> opcList = opcService.queryAll(opc);
		payCycleList(opcList, model, request, orderNo, pageNo);
		return "/order/paycycle";
	}

	private void payCycleList(List<OrderProductCustomer> opc, ModelMap model, HttpServletRequest request, String orderNo, Integer pageNo) {

		List<PayCycle> list = new ArrayList<PayCycle>();
		for (OrderProductCustomer opcc : opc) {
			PayCycle pcc = new PayCycle();
			pcc.setProductName(opcc.getProductName());
			pcc.setPaymentType(opcc.getPaymentType());
			pcc.setProductPrice(opcc.getProductPrice());
			pcc.setProductTime(opcc.getProductTime());
			// PaymentType 1.月 12.年 3.季 6.半年 0. 一次性
			// 月付
			if (pcc.getPaymentType() == 1) {
				for (int i = 1; i < pcc.getProductTime() * 12; i++) {
					// 指定时间输出格式
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

					// Date dt = new Date(); date不能new 使用创建时间相当于传进去一个时间
					// 计算下次付款日期
					Calendar rightNow = Calendar.getInstance();
					rightNow.setTime(opcc.getCreateTime());
					rightNow.add(Calendar.MONTH, i);
					// 计算最终付款日期
					Calendar EndTime = Calendar.getInstance();
					EndTime.setTime(opcc.getCreateTime());
					EndTime.add(Calendar.MONTH, pcc.getProductTime() * 12 - 1);

					PayCycle paycycle = new PayCycle();
					paycycle.setProductName(opcc.getProductName());
					paycycle.setPaymentType(opcc.getPaymentType());
					paycycle.setProductTime(opcc.getProductTime());
					paycycle.setProductPrice(opcc.getProductPrice());
					paycycle.setNextPayTime(sdf.format(rightNow.getTime()));
					paycycle.setHadPay(opcc.getProductPrice() / (pcc.getProductTime() * 12) * i);
					paycycle.setNotPay(opcc.getProductPrice() - opcc.getProductPrice() / (pcc.getProductTime() * 12) * i);
					paycycle.setOverTime(pcc.getOverTime());
					paycycle.setEndTime(sdf.format(EndTime.getTime()));
					list.add(paycycle);
				}
			}
			// 年付
			if (pcc.getPaymentType() == 12) {
				for (int i = 1; i < pcc.getProductTime() * 1; i++) {
					// 指定时间输出格式
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					// 计算下次付款日期
					Calendar rightNow = Calendar.getInstance();
					rightNow.setTime(opcc.getCreateTime());
					rightNow.add(Calendar.YEAR, i);
					// 计算最终付款日期
					Calendar EndTime = Calendar.getInstance();
					EndTime.setTime(opcc.getCreateTime());
					EndTime.add(Calendar.YEAR, pcc.getProductTime() * 1 - 1);

					PayCycle paycycle = new PayCycle();
					paycycle.setProductName(opcc.getProductName());
					paycycle.setPaymentType(opcc.getPaymentType());
					paycycle.setProductTime(opcc.getProductTime());
					paycycle.setProductPrice(opcc.getProductPrice());
					paycycle.setNextPayTime(sdf.format(rightNow.getTime()));
					paycycle.setHadPay(opcc.getProductPrice() / (pcc.getProductTime() * 1) * i);
					paycycle.setNotPay(opcc.getProductPrice() - opcc.getProductPrice() / (pcc.getProductTime() * 1) * i);
					paycycle.setOverTime(pcc.getOverTime());
					paycycle.setEndTime(sdf.format(EndTime.getTime()));
					list.add(paycycle);
				}
			}
			// 季付
			if (pcc.getPaymentType() == 3) {
				for (int i = 1; i < pcc.getProductTime() * 4; i++) {
					// 指定时间输出格式
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					// 计算下次付款日期
					Calendar rightNow = Calendar.getInstance();
					rightNow.setTime(opcc.getCreateTime());
					rightNow.add(Calendar.MONTH, 3 * i);
					// 计算最终付款日期
					Calendar EndTime = Calendar.getInstance();
					EndTime.setTime(opcc.getCreateTime());
					EndTime.add(Calendar.MONTH, pcc.getProductTime() * 12 - 3);

					PayCycle paycycle = new PayCycle();
					paycycle.setProductName(opcc.getProductName());
					paycycle.setPaymentType(opcc.getPaymentType());
					paycycle.setProductTime(opcc.getProductTime());
					paycycle.setProductPrice(opcc.getProductPrice());
					paycycle.setNextPayTime(sdf.format(rightNow.getTime()));
					paycycle.setHadPay(opcc.getProductPrice() / (pcc.getProductTime() * 4) * i);
					paycycle.setNotPay(opcc.getProductPrice() - opcc.getProductPrice() / (pcc.getProductTime() * 4) * i);
					paycycle.setOverTime(pcc.getOverTime());
					paycycle.setEndTime(sdf.format(EndTime.getTime()));
					list.add(paycycle);
				}
			}
			// 半年付
			if (pcc.getPaymentType() == 6) {
				for (int i = 1; i < pcc.getProductTime() * 2; i++) {
					// 指定时间输出格式
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					// 计算下次付款日期
					Calendar rightNow = Calendar.getInstance();
					rightNow.setTime(opcc.getCreateTime());
					rightNow.add(Calendar.MONTH, 6 * i);
					// 计算最终付款日期
					Calendar EndTime = Calendar.getInstance();
					EndTime.setTime(opcc.getCreateTime());
					EndTime.add(Calendar.MONTH, pcc.getProductTime() * 12 - 6);

					PayCycle paycycle = new PayCycle();
					paycycle.setProductName(opcc.getProductName());
					paycycle.setPaymentType(opcc.getPaymentType());
					paycycle.setProductTime(opcc.getProductTime());
					paycycle.setProductPrice(opcc.getProductPrice());
					paycycle.setNextPayTime(sdf.format(rightNow.getTime()));
					paycycle.setHadPay(opcc.getProductPrice() / (pcc.getProductTime() * 2) * i);
					paycycle.setNotPay(opcc.getProductPrice() - opcc.getProductPrice() / (pcc.getProductTime() * 2) * i);
					paycycle.setOverTime(pcc.getOverTime());
					paycycle.setEndTime(sdf.format(EndTime.getTime()));
					list.add(paycycle);
				}
			}
			// 一次性付
			if (pcc.getPaymentType() == 0) {
				for (int i = 1; i <= 1; i++) {
					// 指定时间输出格式
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					// 计算下次付款日期
					Calendar rightNow = Calendar.getInstance();
					rightNow.setTime(opcc.getCreateTime());
					rightNow.add(Calendar.MONTH, 0);
					// 计算最终付款日期
					Calendar EndTime = Calendar.getInstance();
					EndTime.setTime(opcc.getCreateTime());
					EndTime.add(Calendar.MONTH, 0);

					PayCycle paycycle = new PayCycle();
					paycycle.setProductName(opcc.getProductName());
					paycycle.setPaymentType(opcc.getPaymentType());
					paycycle.setProductTime(opcc.getProductTime());
					paycycle.setProductPrice(opcc.getProductPrice());
					paycycle.setNextPayTime(sdf.format(rightNow.getTime()));
					paycycle.setHadPay(opcc.getProductPrice());
					paycycle.setNotPay(0);
					paycycle.setOverTime(pcc.getOverTime());
					paycycle.setEndTime(sdf.format(EndTime.getTime()));
					list.add(paycycle);
				}
			}
		}
		// model.put("list", list);

		// list分页
		List<PayCycle> listCyclist = new ArrayList<PayCycle>();
		Pagination p = new Pagination(Pagination.cpn(pageNo), 5, list.size());
		// p.setPageNo(1);
		p.setPageSize(5);
		int iPageNo = 0;
		if (p.getPageNo() != 1) {
			iPageNo = (p.getPageNo() - 1) * p.getPageSize();
		}
		int iPageSize = p.getPageSize() * (p.getPageNo());
		if (iPageSize > list.size()) {
			iPageSize = list.size();
		}
		// 0 ---5
		// 5 ---(1+1)*5
		// 10---(2+1)*5
		for (int i = iPageNo; i < iPageSize; i++) {
			listCyclist.add(list.get(i));
		}
		p.setList(listCyclist);
		StringBuilder params = new StringBuilder();
		// 拼装 订单号
		params.append("&orderNo=").append(orderNo);
		String url = request.getContextPath() + "/web/order/paycycle.do";
		p.pageView(url, params.toString());
		// p.setPageNo(1);
		// p.setPageSize(5);
		// p.setTotalCount(list.size());
		model.put("page", p);
	}

	/**
	 * 
	 * 描述：签署合同
	 * 创建人： 高磊
	 * 创建时间: 2016-7-5 下午3:07:28
	 * @version
	 * @throws Exception 
	 */
	@RequestMapping("/addContent")
	public String addContent(ModelMap model, String type, String orderNo,String orderId) throws Exception {
		// 获取合同内容
		ContractType contractType = new ContractType();
		contractType.setType(Constants.CONTRACT_TYPE);
		ContractType queryOne = contractTypeService.queryOne(contractType);
		// model.put("contract_content", queryOne.getContent());
		String context = "";
		if (null != queryOne) {
			context = queryOne.getContent();
			// 获取订单内容
			Order order = new Order();
			order.setOrderNo(orderNo);
			Order orderList = orderService.queryOne(order);
			// 获取订单明细
			OrderProductCustomer opc = new OrderProductCustomer();
			opc.setOrderNo(orderNo);
			List<OrderProductCustomer> opcList = opcCustomerService.queryAll(opc);
			model.put("contract_content", replaceContent(orderList, context, opcList));
			model.put("orderNo", orderNo);
			model.put("orderId", orderId);
			replaceContent(orderList, context, opcList);
		}
		System.out.println(context);
		return "/compact/addcompact";
	}

	/**
	 * 
	 * 描述：替换合同内容
	 * 创建人： 高磊
	 * 创建时间: 2016-7-4 下午2:18:29
	 * @version
	 */
	private String replaceContent(Order order, String context, List<OrderProductCustomer> opcList) throws Exception {
		// 乙方替换
		String jfStrReplace = context.replace("<yflianxiren>", "网视通联").replace("<yfdh>", "029-5555").replace("<yfaddress>", "北京市知春路大钟寺");
		// 甲方替换
		String yfStrReplace = jfStrReplace.replace("<jflianxiren>", order.getUserName().toString()).replace("<jfaddress>", order.getUserAddress().toString())
				.replace("<jfdh>", order.getUserPhone().toString());
		// 日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(order.getCreateTime());
		Date d=new Date();
		// 两位随机数
		Random rand = new Random();
		int twoNo = rand.nextInt(89) + 10;
		String xybianhao = yfStrReplace.replace("<xybianhao>", "cchvc" + order.getUserPhone().toString() + sdf.format(rightNow.getTime()).toString() + twoNo).replace("<startTime>", sdf.format(d));
		StringBuilder string = new StringBuilder();
		List<OrderPassVo> orderPassVo = new ArrayList<OrderPassVo>();
		OrderProductCustomer opc = new OrderProductCustomer();
		opc.setOrderNo(order.getOrderNo());
		opc.setProductStatus(1);
		List<OrderProductCustomer> queryAll = opcService.queryAll(opc);
		if (null != queryAll && queryAll.size() > 0) {
			createOrderFieldList(queryAll, orderPassVo);
		}
		float countPrice=0;
		int i = 1;
		for (OrderPassVo opVo : orderPassVo) {
			string.append("<p>产品名称：").append(opVo.getProductName()+"</p>");
			if(opVo.getOrderFieldList().size()>0){
				for(OrderFieldVo of: opVo.getOrderFieldList()){
					
					//当为radio 和select 的时候
					if("radio".equals(of.getFieldType()) || "select".equals(of.getFieldType())){
						for(OrderFieldPriceVo price : of.getFieldTypeValuePrice()){
							if(of.getFieldValue().equals(price.getValue())){
								if(i==2){
									string.append(of.getFieldName()+"：").append(price.getFieldValue()+"</p>");
									i=0;
								}else{
									string.append("<p>"+of.getFieldName()+"：").append(price.getFieldValue()+"&nbsp;&nbsp;&nbsp;");
								}
								i++;
							}
						}
					}
					//当不为radio 和 select 的时候
					boolean isRadio=!("radio").equals(of.getFieldType());
					boolean isSelect=!("select").equals(of.getFieldType());
					boolean isCheckbox=!("checkbox").equals(of.getFieldType());
					if(isRadio && isSelect && isCheckbox){
						if(i==2){
							i=0;
							string.append(of.getFieldName()+"：").append(of.getFieldValue()+"</p>");
						}else{
							string.append("<p>"+of.getFieldName()+"：").append(of.getFieldValue()+"&nbsp;&nbsp;&nbsp;");
						}
						i++;
					}
					
					//当为checkbox 的时候
					
					if("checkbox".equals(of.getFieldType())){
						if(i==2){
							i=0;
							string.append(of.getFieldName()+"：").append(of.getFieldValue()+"</p>");
						}else{
							string.append("<p>"+of.getFieldName()+"：").append(of.getFieldValue()+"&nbsp;&nbsp;&nbsp;");
						}
						i++;
					}
				}
			}
			
			string.append("<p>产品价格：").append(opVo.getProductPrice()+"</p>");
			countPrice=countPrice+opVo.getProductPrice();
		}
		string.append("<p>订单总价：").append(countPrice+"</p>");
		/*int i = 1;
		for (String key : map.keySet()) {
			// 每两个换一行
			if (i == 2) {
				string.append(key + ":").append(map.get(key) + "<br>");
				i = 0;
			} else {
				string.append(key + ":").append(map.get(key) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
			}
			i++;
		}*/
		String orderMx = xybianhao.replace("<orderdetail>", string.toString());
		return orderMx;
	}

}
